package com.bestcem.xm.ticket.dao.impl.mysql;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.ticket.dao.RspdTimerDao;
import com.bestcem.xm.ticket.dao.converter.RspdTimerConverter;
import com.bestcem.xm.ticket.dao.mapper.RspdTimerDaoMapper;
import com.bestcem.xm.ticket.entity.mongo.RspdTimer;
import com.bestcem.xm.ticket.entity.mysql.RspdTimerDO;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/9/17 18:55
 */
@Repository
public class RspdTimerDaoImpl implements RspdTimerDao {

    @Resource
    private RspdTimerDaoMapper rspdTimerDaoMapper;

    @Override
    public RspdTimer findById(String id) {
        return rspdTimerDaoMapper.findById(id);
    }

    @Override
    public void saveRespondentTimer(RspdTimer entity) {
        RspdTimerDO entityDo = RspdTimerConverter.dtoToDo(entity);
        if (Objects.isNull(entityDo)) {
            return;
        }

        if (Objects.isNull(entityDo.getRspdTimerId())) {
            entityDo.setRspdTimerId(ObjectId.next());
        }

        if (Objects.isNull(entityDo.getCreateTime())) {
            entityDo.setCreateTime(DateUtil.getCommonDate());
        }
        if (Objects.isNull(entityDo.getUpdateTime())) {
            entityDo.setUpdateTime(DateUtil.getCommonDate());
        }

        rspdTimerDaoMapper.insert(entityDo);
    }

    @Override
    public List<RspdTimer> findTimerByExpire(Long curTime, Long oldTime, Integer status) {
        List<RspdTimerDO> rspdTimerDOList = rspdTimerDaoMapper
                .findByExpireBetween(curTime.intValue(), oldTime.intValue(), status);
        return RspdTimerConverter.doListToDtoList(rspdTimerDOList);
    }

    @Override
    public void updateTimer(String id, Integer expire) {
        rspdTimerDaoMapper.updateExpireByRspdTimerId(id, expire, DateUtil.getCommonDate());
    }

    @Override
    public void updateTimerStatus(String id, Integer status) {
        rspdTimerDaoMapper.updateTimerStatus(id, status);
    }
}
